package test

import (
	"context"
	"flag"
	"fmt"
	"log"
	"time"

	pb "awesome/proto"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

var serAddr = flag.String("addr", "localhost:8000", "the address to connect to")

func main() {
	// 解析命令行参数
	flag.Parse()

	name, age := f2()
	fmt.Println(name, age)

	// 连接服务端
	conn, err := grpc.Dial(*serAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("连接服务器失败: %v", err)
	}
	log.Printf("建立连接成功: %s", *serAddr)
	// 执行完方法自动关闭资源
	defer conn.Close()

	// 创建客户端
	c := pb.NewGreeterClient(conn)

	log.Println("5秒中之后调用SayHello方法")
	time.Sleep(time.Second * 5)
	// 创建2秒超时ctx
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
	defer cancel()
	// 发起RPC请求
	log.Println("开始调用SayHello方法")
	res, err := c.SayHello(ctx, &pb.HelloRequest{Name: "一号"})
	if err != nil {
		log.Fatalf("请求失败: %v", err)
	}
	log.Printf("请求结果: %s", res.GetMessage())

	// 睡眠一会再结束
	log.Println("3秒后结束，客户端自动断开连接")
	time.Sleep(time.Second * 3)

}
